/* eslint-disable array-callback-return */
import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { DoubleRightOutlined, DownloadOutlined, UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Upload, Modal, Progress, message } from 'antd';
import downloadFile, { urlParse } from '@/utils/utils';

let subinterval = null;

@connect(({ quoupdate, loading, location }) => ({
  quoupdate,
  loading: loading.models.quoupdate,
  getBatchId: quoupdate.getBatchId, // 第二步到第三步的批次号
  batchId: quoupdate.batchId, // 上传后的批次号
  location,
  changQuoUpdateMessage: quoupdate.changQuoUpdateMessage,
}))
@Form.create()
class FileUpload extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      fileList: [],
      quoId: '',
      quoState: '',
      batchNumber: '',
      subProgressVisible: false, // 提交时的进度弹框
      subprogressPercent: 0, // 提交时的进度
      btn: null, // 1是有增产品
      fileLength: 1,
    };
  }

  componentDidMount() {
    const { history, changQuoUpdateMessage, dispatch } = this.props;
    const { quoId, quoState, batchNumber, btn } = urlParse(history.location.search);
    if (btn === '2') {
      dispatch({
        type: 'quoupdate/updateModelData',
        payload: {
          showProgress: true,
          isSubmitResult: false,
        },
      });
      dispatch({
        type: 'quoupdate/uploadFileHasProduct',
        payload: { batchId: changQuoUpdateMessage.batchNo },
      });
    } else {
      dispatch({
        type: 'quoupdate/updateModelData',
        payload: {
          showProgress: false,
        },
      });
    }
    this.setState({
      quoId,
      quoState,
      batchNumber,
      btn,
    });
  }

  // 上传文件
  uploadFiles = fileData => {
    const { uploadFile } = this.props;
    const formData = new FormData();
    formData.append('file', fileData);
    uploadFile(formData);
    return false;
  };

  removeFile = file => {
    this.setState(state => {
      const index = state.fileList.indexOf(file);
      const newFileList = state.fileList.slice();
      newFileList.splice(index, 1);
      return {
        fileList: [],
        fileLength: 1,
      };
    });
  };

  submitData = () => {
    const { quoupdate, dispatch, batchId, changQuoUpdateMessage } = this.props;
    const { quoId, quoState, btn } = this.state;
    const submitData = quoupdate.nextData;
    if (submitData && submitData.packList) {
      submitData.packList.map(packitem => {
        const temp = packitem;
        delete temp.listIndex;
        delete temp.allAreaId;
        packitem.listQuoPd.map(quoPditem => {
          const obj = quoPditem;
          delete obj.listInfo;
          delete obj.listArear;
          delete obj.aleadyAttr;
          delete obj.pdAttrVOs;
          delete obj.listAttrPrice;
          delete obj.newListArear;
          delete obj.newlistInfo;
        });
        packitem.priceList.map(pritem => {
          const tempObj = pritem;
          delete tempObj.areaIdList;
          delete tempObj.areaList;
          delete tempObj.areaNameList;
          delete tempObj.id;
          delete tempObj.areaName;
          delete tempObj.areaIds;
          tempObj.areaId = Array.isArray(pritem.areaId)
            ? pritem.areaId && pritem.areaId.join(',')
            : pritem.areaId;
          if (pritem.dicTaxFlag) {
            delete tempObj.dicTaxFlag;
          }
        });
      });
    }

    if (btn === '1') {
      submitData.orderbatchNo = batchId || null;
    } else {
      submitData.orderbatchNo = changQuoUpdateMessage.batchNo || null;
    }
    dispatch({
      type: 'quoupdate/updateSubmit',
      payload: submitData,
      callback: res => {
        if (res.success) {
          dispatch({
            type: 'quoupdate/submitWithProgress',
            payload: {
              routerParam: { quoId, quoState },
            },
          });
        } else {
          message.warning(`${res.message || '提交失败，服务端未知错误'}`);
        }
      },
    });
  };

  // 进度弹框显隐
  subHandleProgressModal = flag => {
    this.setState({
      subProgressVisible: !!flag,
      subprogressPercent: 0,
    });
    if (!flag) {
      clearInterval(subinterval);
    }
  };

  // 下载失败原因
  downloadErrorInfo = () => {
    const { batchId } = this.props;
    const { batchNumber } = this.state;
    const params = {
      cacheKey: batchNumber,
      batchId,
    };
    downloadFile(params, '/csApi/sendempchangeQuo/exportErrorExcel', 'POST');
  };

  render() {
    const {
      uploading,
      progressTitle = '上传进度条',
      progressPercent,
      isExact,
      preStep = () => {
        router.goBack();
      },
      resultInfo,
      quoupdate,
    } = this.props;
    const {
      fileList,
      quoId,
      subProgressVisible,
      batchNumber,
      subprogressPercent,
      btn,
      fileLength,
    } = this.state;
    const props = {
      beforeUpload: file => {
        const isLimitsize = file.size / 1024 / 1024 < 5; // 文件限制5M
        if (!isLimitsize) {
          message.warning(
            `为了保证系统能够快速响应，上传文件大小不能超过${5}M，如数据量太多，建议拆分后分批上传！`
          );
        } else {
          const fileTye = [
            // 默认限制类型，excel,传空数组表示不限制类型,或者传文件其他类型
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'xlsx',
            'xls',
          ];
          const isType = !file.type ? file.name && file.name.split('.')[1] : file.type;
          const isExcel = fileTye.indexOf(isType) > -1;
          if (!isExcel) {
            this.setState({ fileList: [], fileLength: 1 });
            message.warning('文件格式错误，只能上传excel表格格式!');
          } else if (fileLength === 1) {
            this.setState(
              {
                fileList: [...fileList, file],
                fileLength: 2,
              },
              () => {
                this.uploadFiles(file);
              }
            );
          } else {
            this.setState({
              fileLength: 2,
            });
            message.warning('建议一次只能上传一个文件');
          }
        }
        return false;
      },
      fileList,
      onRemove: file => {
        this.removeFile(file);
      },
    };
    return (
      <Form layout="horizontal">
        {isExact ? <this.props.isExact /> : null}
        {btn === '1' ? (
          <p style={{ margin: '0 auto', width: '90%', fontSize: 14, textAlign: 'left' }}>
            <span style={{ fontWeight: 600, fontSize: '16px' }}>产品增加或减少</span>
            <span style={{ color: '#999999' }}>
              （存在增产品或减产品需要先下载人员信息，补充信息之后上传）
            </span>
          </p>
        ) : null}
        {btn === '1' ? (
          <div
            style={{
              width: 480,
              height: 200,
              margin: '0 auto',
              marginTop: 50,
              textAlign: 'center',
            }}
          >
            <Button
              icon={<DownloadOutlined />}
              onClick={() =>
                downloadFile(
                  { cacheKey: batchNumber, quoId },
                  `/csApi/sendempchangeQuo/downloadEmp`,
                  'POST'
                )
              }
              style={{ zIndex: 88, marginRight: 8 }}
            >
              下载所有数据
            </Button>
            <DoubleRightOutlined
              style={{
                display: 'block',
                margin: '20px auto',
                fontSize: 30,
                transform: 'rotate(90deg)',
              }} />
            <Upload {...props}>
              <Button>
                <UploadOutlined />
                上传
              </Button>
            </Upload>
          </div>
        ) : null}
        <div
          style={{
            width: 480,
            margin: '0 auto',
            textAlign: 'center',
          }}
        >
          {btn === '1' ? (
            <div>
              {resultInfo.batchId && fileList.length ? (
                <p style={{ margin: '20px 0 0 0' }}>
                  验证结果：成功{resultInfo.successCount}条；
                  <span style={{ color: 'red' }}>失败{resultInfo.errorCount}条；</span>
                  {resultInfo.errorCount === 0 ? null : (
                    <a onClick={this.downloadErrorInfo}>下载查看失败原因</a>
                  )}
                </p>
              ) : null}
            </div>
          ) : (
            <div>
              {resultInfo.batchId ? (
                <p style={{ margin: '20px 0 0 0' }}>
                  验证结果：成功{resultInfo.successCount}条；
                  <span style={{ color: 'red' }}>失败{resultInfo.errorCount}条；</span>
                  {resultInfo.errorCount === 0 ? null : (
                    <a onClick={this.downloadErrorInfo}>下载查看失败原因</a>
                  )}
                </p>
              ) : null}
            </div>
          )}
        </div>
        {/* 上传的收的进度 */}
        <Modal
          title={progressTitle || '正在提交'}
          footer={null}
          closable={false}
          maskClosable={false}
          visible={quoupdate.showProgress}
          destroyOnClose
        >
          <div style={{ textAlign: 'center' }}>
            <Progress percent={progressPercent} format={percent => `${percent}%`} />
          </div>
        </Modal>
        {/* 提交的时候的进度 */}
        <Modal
          title="正在提交"
          footer={null}
          closable={false}
          maskClosable={false}
          visible={subProgressVisible}
          onCancel={() => this.subHandleProgressModal()}
        >
          <div style={{ textAlign: 'center' }}>
            <Progress percent={subprogressPercent} format={percent => `${percent}%`} />
          </div>
        </Modal>
        <div style={{ textAlign: 'center', marginTop: 100 }}>
          <Button onClick={() => preStep()} style={{ marginRight: 8 }}>
            上一步
          </Button>
          {btn === '2' ? (
            <Button
              type="primary"
              onClick={this.submitData}
              loading={uploading}
              disabled={!!(resultInfo.batchId && resultInfo.errorCount !== 0)}
            >
              提交
            </Button>
          ) : (
            <Button
              type="primary"
              onClick={this.submitData}
              loading={uploading}
              disabled={
                resultInfo.batchId && fileList.length
                  ? resultInfo.errorCount !== 0
                  : !(resultInfo.batchId && fileList.length)
              }
            >
              提交
            </Button>
          )}
        </div>
      </Form>
    );
  }
}

export default FileUpload;
